package com.frinder.hadoop.hdfs;

import io.swagger.annotations.ApiOperation;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.hadoop.fs.FsShell;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.stream.Collectors;

/**
 * @author frinder
 * @date 2018/6/20
 * @Description: ${todo}
 */
@RestController
@RequestMapping("/hadoop")
public class HadoopController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private FsShell shell;

    /**
     * list 显示目录
     *
     * @param path
     * @return
     */
    @ApiOperation("list指定目录下文件列表")
    @GetMapping("/list")
    public Object list(@RequestParam(defaultValue = "/") String path) {
        Collection<FileStatus> files = shell.lsr(path);
        logger.info("List Files: {}", files);
        return files.stream().map(f -> f.getPath().getName()).collect(Collectors.toList());
    }

    @ApiOperation("上传文件")
    @GetMapping("/put")
    public String put() {
        shell.put("E:\\git\\learn\\hadoop-learning\\file3.txt", "/user/input");
        return "successfully";
    }

    @ApiOperation("上传指定文件到指定目录")
    @GetMapping("/put/to")
    public String put(@RequestParam String sFile, @RequestParam String dest) {
        shell.put(sFile, dest);
        return "successfully";
    }

    @ApiOperation("下载文件")
    @GetMapping("/get")
    public String get() {
        shell.get("/user/input/file.txt", "E:\\git\\learn\\hadoop-learning");
        return "successfully";
    }

    @ApiOperation("查看文件内容")
    @GetMapping("/cat")
    public Object cat() {
        Collection<Path> paths = shell.cat("/user/input/file.txt");
        logger.info("Paths: {}", paths);
        return String.valueOf(paths);
    }

}
